import {
  indexApi
} from '../../../api/index';
import {
  request
} from '../../../utils/request';

import Toast from '@vant/weapp/toast/toast';
Page({
  data: {
    defaultData: {
      title: "添加报表模板", // 导航栏标题
      imageSrc: "/images/back.png",
      isBackToPreviousPage: true
    },
    checked: false, //默认地址复选框
    isDefault: 0,
    tpName: null, //模板名称
    documentTitle: null, //模板标题
    introduction: null, //产品简介
    fileListLog: [], // log图片的列表
    fileListHome: [], // 首页图片的列表
    functionAplication: null, // 功能应用
    fromPage: null,
    templateId: null,
    sceneList: [],
    checkedSceneList: [], // 选中的场景ID列表
    checkedSceneNameList: [], // 选中的场景名称列表
    showSceneDialog: false,
    newSceneName: ""
  },

  onLoad(options) {
    this.getSceneFunction().then(() => {
      if (options.templateItem) {
        const templateItem = JSON.parse(decodeURIComponent(options.templateItem));
        const selectedSceneNames = templateItem.param2.split(',').map(item => item.trim());
        console.log("selectedSceneNames", selectedSceneNames);
        const checkedScenes = [];
        const checkedSceneNames = [];

        selectedSceneNames.forEach(name => {
          const scene = this.data.sceneList.find(item => item.name == name);
          if (scene) {
            checkedScenes.push(scene.sid);
            checkedSceneNames.push(scene);
          } else {
            const uniqueId = `scene_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
            checkedSceneNames.push({
              sid: uniqueId,
              name: name
            });
          }
        });

        this.setData({
          templateId: templateItem.id,
          tpName: templateItem.tpName,
          documentTitle: templateItem.title,
          introduction: templateItem.param1,
          functionAplication: templateItem.param3,
          fileListLog: templateItem.logoUrl ? [{
            url: templateItem.logoUrl
          }] : [],
          fileListHome: templateItem.headUrl ? [{
            url: templateItem.headUrl
          }] : [],
          checkedSceneList: checkedScenes,
          checkedSceneNameList: checkedSceneNames
        });

      }

      if (options.fromPage) {
        this.setData({
          fromPage: options.fromPage
        });
        console.log("options.fromPage", this.data.fromPage);
      }
    }).catch(err => {
      console.error("获取场景失败", err);
    });
  },

  // 获取场景功能
  async getSceneFunction() {
    try {
      let a = "SCENE_FUNCTION";
      const res = await request({
        url: indexApi.getSysDicApi(a),
        data: {}
      });
      const sceneListWithSid = res.data.map((item) => {
        return {
          ...item,
          sid: `${item.id || ''}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}` // 生成唯一的sid
        };
      });

      this.setData({
        sceneList: sceneListWithSid
      });
    } catch (error) {
      console.error("Error:", error);
    }
  },

  //复选框的变更
  onSceneChange(event) {
    console.log("event", event);
    const selectedIds = event.detail.map(id => String(id));
    const selectedScenes = this.data.sceneList.filter(item =>
      selectedIds.includes(item.sid)
    );
    // 合并场景名称列表
    const mergedSceneNameList = [
      ...selectedScenes,
      ...this.data.checkedSceneNameList.filter(item => !this.data.sceneList.some(scene => scene.sid === item.sid))
    ];
    // 检查合并后的场景名称列表长度
    if (mergedSceneNameList.length > 10) {
      wx.showToast({
        title: '最多不能超过10个选项',
        icon: 'none'
      });
      return;
    }
    this.setData({
      checkedSceneList: selectedIds,
      checkedSceneNameList: mergedSceneNameList
    });
    console.log("Selected scene IDs:", this.data.checkedSceneList);
    console.log("Selected scene names:", this.data.checkedSceneNameList);
  },


  addScene() {
    this.setData({
      showSceneDialog: true
    })
  },
  onClose() {
    this.setData({
      showSceneDialog: false
    });
  },

  addSceneChange(event) {
    this.setData({
      newSceneName: event.detail
    });
    console.log("输入新增的场景", this.data.newSceneName);
  },


  // 点击确定按钮，确认新增场景
  onConfirmScene() {
    const newSceneName = this.data.newSceneName;
    console.log("newSceneName", newSceneName);

    // 检查是否为空
    if (!newSceneName) {
      wx.showToast({
        title: '场景名称不能为空',
        icon: 'none'
      });
      return;
    }

    // 检查输入的名称是否已在 checkedSceneNameList 中存在 智能计量节能
    const isDuplicate = this.data.checkedSceneNameList.some(item => item.name == newSceneName);
    if (isDuplicate) {
      wx.showToast({
        title: '场景名称重复',
        icon: 'none'
      });
      this.setData({
        newSceneName: ''
      });
      return;
    }

    // 检查输入的名称是否在 sceneList 中存在
    const isSystemScene = this.data.sceneList.some(item => item.name == newSceneName);
    if (isSystemScene) {
      wx.showToast({
        title: '请在系统场景功能中选择此场景',
        icon: 'none'
      });
      this.setData({
        newSceneName: ''
      });
      return;
    }

    // 检查 checkedSceneNameList 的长度是否已达到 10
    if (this.data.checkedSceneNameList.length >= 10) {
      wx.showToast({
        title: '最多不能超过10个选项',
        icon: 'none'
      });
      this.setData({
        newSceneName: ''
      })
      return;
    }

    const newScene = {
      sid: `scene_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      name: newSceneName
    };

    this.setData({
      checkedSceneNameList: [...this.data.checkedSceneNameList, newScene],
      newSceneName: ''
    });

    console.log("新增场景", newScene);
    console.log("Updated checkedSceneNameList", this.data.checkedSceneNameList);
  },


  // 删除场景
  delScene(event) {
    const sidToDelete = event.currentTarget.dataset.sid;
    const updatedSceneNameList = this.data.checkedSceneNameList.filter(item => item.sid !== sidToDelete);
    const updatedSceneList = this.data.checkedSceneList.filter(sid => sid !== sidToDelete);

    this.setData({
      checkedSceneNameList: updatedSceneNameList,
      checkedSceneList: updatedSceneList
    });
  },


  //默认模板
  onChange(event) {
    this.setData({
      checked: event.detail,
    });
    console.log("checked", this.data.checked);
    const isDefault = this.data.checked ? 1 : 0;
    this.setData({
      isDefault: isDefault,
    });
    console.log("isDefault", this.data.isDefault);
  },

  //模板名称
  tpNameChange(event) {
    this.setData({
      tpName: event.detail,
    });
    console.log("tpName", this.data.tpName);
  },

  //文档标题
  titleChange(event) {
    this.setData({
      documentTitle: event.detail,
    });
    console.log("documentTitle", this.data.documentTitle);
  },

  //产品简介
  IntroductionChange(event) {
    this.setData({
      introduction: event.detail,
    });
    console.log("introduction", this.data.introduction);
  },

  //功能应用
  applicationChange(event) {
    this.setData({
      functionAplication: event.detail,
    });
    console.log("functionAplication", this.data.functionAplication);
  },


  // 上传图片
  afterRead(event) {
    const {
      file
    } = event.detail;
    const type = event.currentTarget.dataset.type;

    if (file.size > 200 * 1024) { // 超过200k则压缩
      wx.compressImage({
        src: file.url,
        quality: 80, // 压缩质量，范围1-100，越低压缩率越高
        success: (res) => {
          file.url = res.tempFilePath; // 更新文件路径为压缩后的图片
          this.uploadFile(file, type);
        },
        fail: () => {
          wx.showToast({
            title: '图片压缩失败',
            icon: 'none'
          });
        }
      });
    } else {
      this.uploadFile(file, type); // 不需要压缩，直接上传
    }
  },

  async uploadFile(file, type) {
    try {
      const uploadTask = wx.uploadFile({
        url: indexApi.upLoadApi(),
        header: {
          "Content-Type": "multipart/form-data"
        },
        filePath: file.url,
        name: 'file',
        formData: {},
        success: (res) => {
          const data = JSON.parse(res.data);
          console.log('Upload success', data);
          file.url = data.data;
          if (type === 'log') {
            this.setData({
              fileListLog: [file]
            });
            console.log("fileListLog", this.data.fileListLog);
          } else if (type === 'home') {
            this.setData({
              fileListHome: [file]
            });
            console.log("fileListHome", this.data.fileListHome);
          }
        },
        fail: (err) => {
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          });
        },
      });
    } catch (error) {
      wx.showToast({
        title: '上传失败,请联系管理员',
        icon: 'none'
      });
    }
  },

  // 删除图片回调
  onDelete(event) {
    const type = event.target.dataset.type;
    if (type === 'log') {
      this.setData({
        fileListLog: []
      });
    } else if (type === 'home') {
      this.setData({
        fileListHome: []
      });
    }
  },


  //保存
  async saveTemplate() {
    const {
      tpName,
      documentTitle,
      introduction,
      fileListLog,
      fileListHome,
      isDefault,
      templateId,
      functionAplication,
      checkedSceneNameList
    } = this.data;
    let logoUrl = '';
    let headUrl = '';

    // 校验表单
    if (!tpName) {
      Toast('请输入模板名称');
      return;
    }
    if (!documentTitle) {
      Toast('请输入文档标题');
      return;
    }
    if (!introduction) {
      Toast('请输入产品简介');
      return;
    }
    if (fileListLog.length == 0) {
      Toast('请上传log图片');
      return;
    } else {
      logoUrl = fileListLog[0].url;
      console.log("logoUrl", logoUrl);
    }
    if (fileListHome.length == 0) {
      Toast('请上传首页图片');
      return;
    } else {
      headUrl = fileListHome[0].url;
      console.log("headUrl", headUrl);
    }
    if (!functionAplication) {
      Toast('请输入功能应用');
      return;
    }
    const param2 = checkedSceneNameList.map(item => item.name).join(',');
    // 创建请求参数对象
    let requestData = {
      tpName: tpName,
      title: documentTitle,
      param1: introduction,
      logoUrl: logoUrl,
      headUrl: headUrl,
      param3: functionAplication,
      param2: param2
    };

    // 如果 isDefault 为 1，则添加 isDefault 字段
    if (isDefault === 1) {
      requestData.isDefault = isDefault;
    }
    if (templateId !== null) {
      requestData.id = this.data.templateId;
    }

    try {
      const res = await request({
        url: indexApi.saveReportTemplateApi(),
        method: "POST",
        data: requestData, // 动态请求数据
      });

      if (res.code == 200 && templateId == null) {
        console.log("templateId", templateId);
        wx.showToast({
          title: "添加成功",
          icon: "none",
        });
      }
      if (res.code == 200 && templateId !== null) {
        console.log("templateId", templateId);
        wx.showToast({
          title: "修改成功",
          icon: "none",
        });
      }
      console.log("res", res);

      setTimeout(() => {
        wx.navigateBack();
      }, 1000);
    } catch (error) {
      console.error("Error:", error);
    }
  },


  toBack() {
    wx.navigateBack({
      delta: 1
    });
  },
  
})